package com.mentalhealth.diary.common;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT拦截器
 * 用于拦截需要认证的接口，验证JWT令牌
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    /**
     * 请求处理前执行
     * 验证JWT令牌
     * @param request 请求
     * @param response 响应
     * @param handler 处理器
     * @return 是否继续执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 从请求头获取Authorization
        String authorization = request.getHeader("Authorization");
        
        // 提取JWT令牌
        String token = JwtUtil.extractTokenFromBearer(authorization);
        
        // 如果令牌不存在，抛出异常
        if (token == null) {
            throw new BusinessException(401, "请先登录哦～");
        }
        
        // 验证令牌并获取用户ID
        Long userId = JwtUtil.getUserIdFromToken(token);
        
        // 将用户ID存储到请求属性中，供后续使用
        request.setAttribute("userId", userId);
        
        // 继续执行请求
        return true;
    }
}